import { getFeeListApi, shiftOrOutCostApi } from "@/api/financialManagement/receivable/statement";
import FormHook from "@/hook/formHook";
import { message } from "ant-design-vue";
import { computed, Ref } from "vue";

export default function OperationHook(state: {
  searchForm: ReceivableStatement.AddFeeSearchForm;
  loading: Ref<boolean>;
  tableData: Ref<Array<Base.GeneraDataType>>;
  passData: Ref<ReceivableStatement.ListRows[]>;
  tableRef: Ref<any>;
  emit: any;
}) {
  const { searchForm, loading, tableData, passData, tableRef, emit } = state;
  const selectRows = computed<Array<Base.GeneraDataType>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { resetFields } = FormHook({ formState: searchForm });
  const getData = () => {
    loading.value = true;
    const params: any = {
      ...searchForm,
      customerId: passData.value[0].customerId,
      channelId: searchForm.channelId.length ? searchForm.channelId[2] : ""
    };
    if (params.waybillNums) {
      params.waybillNums = params.waybillNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    } else {
      params.waybillNums = [];
    }
    return getFeeListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const searchHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };
  const addFeeHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选费用!");
    console.log(passData.value);
    shiftOrOutCostApi({ isShiftIN: 1, costIds: selectRows.value.map((t: any) => t.id), receivableBillId: passData.value[0].id }).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("移入成功!");
        emit("submit");
      }
    });
  };
  return {
    searchHandle,
    getData,
    resetFields,
    addFeeHandle
  };
}
